<template>
  <div style="padding:30px;">

    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-dark">
          <h4>添加进货订单</h4>
          <el-divider></el-divider>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-form ref="topForm" :model="topForm">
        <el-col :span="8">
          <el-form-item label="选择供货商">
            <el-select v-model="topForm.supplierId" placeholder="请选择供货商">
              <el-option label="供货商一" value="1"></el-option>
              <el-option label="供货商二" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="选择进货仓库">
            <el-select v-model="topForm.depotId" placeholder="请选择进货仓库">
              <el-option label="仓库一" value="1"></el-option>
              <el-option label="仓库二" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进货时间">
            <el-date-picker v-model="topForm.creatTime" value-format="yyyy-MM-dd HH:mm:ss" align="right" type="date" placeholder="选择日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>


      </el-form>
    </el-row>

    <el-table :data="table" :border=true style="width: 100%;">
      <el-table-column prop="id" label="编号" width="50"></el-table-column>
      <el-table-column prop="name" label="商品名称" width="300">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" placeholder="请选择商品" @click.native="addproduct(scope.$index, scope.row)">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="商品数量" width="100"> </el-table-column>
      <el-table-column prop="unit" label="商品规格" width="100"> </el-table-column>
      <el-table-column prop="price" label="单价" width="100"> </el-table-column>
      <el-table-column prop="subtotal" label="小计" width="100"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" plain @click="delmembers(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <i class="el-icon-circle-plus-outline" @click="addmembers"></i>


    <el-form ref="topForm" :inline="true" :model="topForm">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-form-item label="总计:">
              <span>{{topForm.total}} </span>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="应付:">
              <span>{{topForm.total}} </span>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-form-item label="实付:">
              <el-input v-model="topForm.trueTotal"></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-form-item label="备注">
              <el-input v-model="topForm.remark"></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="支付方式：">
              <el-select v-model="topForm.payment" placeholder="请选择进货仓库">
                <el-option label="微信" value="微信"></el-option>
                <el-option label="支付宝" value="支付宝"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="addPurchase()">提交</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog title="选择商品" :visible.sync="addproducts" width="800px">
      <input type="hidden" v-model="index" />
      <el-table ref="filterTable" :data="addTable" style="width: 100%">
        <el-table-column prop="num" label="序号" width="180"></el-table-column>
        <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
        <el-table-column prop="jin" label="商品进价" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.jin" placeholder="请输入商品进价"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="standby2" label="商品数量" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.standby2" placeholder="请输入商品数量"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="danWei" label="商品单位" width="180"></el-table-column>
        <el-table-column prop="remark" label="商品备注" width="180"></el-table-column>
        <el-table-column prop="state" label="商品状态" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="selectChecked(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import { show } from '@/api/product'
   import { add  } from '@/api/purchase'
   import { addInfo  } from '@/api/purchaseInfo'
  export default {
    data() {
      return {
        topForm: {
          supplierId: '',
          creatTime: '',
          total: 0,
          payment: '',
          depotId: '',
          trueTotal: '',
          num: 0
        },
        table: [{
          id: '',
          codeId: '',
          name: '',
          num: '',
          state: '',
          remark: ''
        }],

        addproducts: false,
        addTable: [],
        index: '',

        pickerOptions: {
          disabledDate(time) {
            return time.getTime() + 3600 * 1000 * 24 <= Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '明天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '后天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
              picker.$emit('pick', date);
            }
          }]
        },
      };
    },
    methods: {
      addmembers() {
        let length = this.table.length;
        this.table.push({
          id: '',
          codeId: '',
          name: '',
          num: '',
          state: '',
          remark: ''
        })
      },
      delmembers(index, row) {
        if (index == 0) {
          this.$message({
            showClose: true,
            message: '请至少保留一行',
            type: 'error'
          });
        } else {
          this.$confirm('确认删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //点击确定的操作
            var hasmembers = this.table;
            for (var i = 0; i < hasmembers.length; i++) {
              if (row.id == hasmembers[i].id) {
                hasmembers.splice(i, 1);
              }
            }
          }).catch(() => {
            return;
          });
        }
      },
      addproduct(index, row) {
        this.addproducts = true;
        this.index = index;
        return new Promise((resolve, reject) => {
          show({}).then(response => {
            const {
              data,
              count
            } = response
            this.addTable = data;
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      selectChecked(row) {
        const {
          id,
          name,
          jin,
          danWei,
          standby2
        } = row;
        if (jin == null) {
          this.$message({
            showClose: true,
            message: '进价不能为空',
            type: 'error'
          });
          return false;
        } else {
          if (standby2 == null) {
            this.$message({
              showClose: true,
              message: '数量不能为空',
              type: 'error'
            });
            return false;
          } else {
             this.table[this.index].id = id;
            this.table[this.index].name = name;
            this.table[this.index].price = jin;
            this.table[this.index].unit = danWei;
            this.table[this.index].num = standby2;
            this.table[this.index].subtotal = jin * standby2;
            this.topForm.total += jin * standby2;
            this.topForm.num += 1;
            this.addproducts = false;
          }
        }
      },
      addPurchase(){
         return new Promise((resolve, reject) => {
           add({
             'creatTime' : this.topForm.creatTime,
             'depotId' : this.topForm.depotId,
             'supplierId' : this.topForm.supplierId,
             'num' : this.table.length,
             'total' : this.topForm.trueTotal,
             'state' : 0,
             'userId' : null,
             'payment': this.topForm.payment,
             'remark' : this.topForm.remark,
             }).then(response => {
               let rs=true;
               const purchaseId=response.count;
               this.table.forEach(function(el) {
                 return new Promise((resolve, reject) => {
                   addInfo({
                       'productId' : el.id,
                       'productName' : el.name,
                       'purchaseId' : purchaseId,
                       'unit' : el.unit,
                       'price' : el.price,
                       'subtotal' : el.subtotal,
                       'standby2' : el.num
                     }).then(responseInfo => {
                      if(!responseInfo.data){
                        rs=false;
                      }
                     resolve()
                   }).catch(error => {
                     reject(error)
                   })
                 })
               });
               // 'listInfo' : info
               if(rs){
                 this.$message({
                   showClose: true,
                   message: '提交成功',
                   type: 'success',
                   onClose:  () =>{
                      location.reload();
                   }
                 });
               }else{
                 this.$message({
                   showClose: true,
                   message: '提交失败',
                   type: 'error'
                 });
               }
             resolve()
           }).catch(error => {
             reject(error)
           })
         })
      }

    }
  };
</script>
